<?php

namespace app\admin\controller\user;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use fast\Tree;
use think\Collection;
use think\Db;
use think\Env;
use think\Log;

/**
 * 学员管理
 * 为学校管理员和社区管理员提供学员管理功能
 *
 * @icon fa fa-graduation-cap
 */
class Studentmanager extends Backend
{
    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname,mobile';
    //给changeStatus和export权限
    protected $noNeedRight = ["lists","status",'changeStatus', 'export', 'testExport'];
    protected $noNeedLogin = ["lists","status",'changeStatus', 'export', 'testExport'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            // 获取当前用户的用户组
            $currentUserGroups = $this->auth->getGroups();
            $allowedGroupIds = [];

            // 直接从数据库查询子组，避免Tree实例问题
            foreach ($currentUserGroups as $currentGroup) {
                // 添加当前用户组（同级）
                $allowedGroupIds[] = $currentGroup['id'];

                // 从groupList中查找直接子组
                foreach ($groupList as $group) {
                    if ($group['pid'] == $currentGroup['id']) {
                        $allowedGroupIds[] = $group['id'];
                    }
                }
            }

            // 去重并过滤
            $allowedGroupIds = array_unique($allowedGroupIds);
            $allowedGroupIds = array_intersect($allowedGroupIds, $this->childrenGroupIds);

            // 构建分组数据 - 简化逻辑
            $result = [];
            foreach ($currentUserGroups as $currentGroup) {
                $temp = [];

                // 添加当前组
                if (in_array($currentGroup['id'], $allowedGroupIds)) {
                    $temp[$currentGroup['id']] = $currentGroup['name'];
                }

                // 添加子组
                foreach ($groupList as $group) {
                    if ($group['pid'] == $currentGroup['id'] && in_array($group['id'], $allowedGroupIds)) {
                        $temp[$group['id']] = $group['name'];
                    }
                }

                if (!empty($temp)) {
                    $result[__($currentGroup['name'])] = $temp;
                }
            }

            // 如果结果为空，至少显示当前用户组
            if (empty($result) && !empty($currentUserGroups)) {
                $temp = [];
                foreach ($currentUserGroups as $currentGroup) {
                    if (in_array($currentGroup['id'], $this->childrenGroupIds)) {
                        $temp[$currentGroup['id']] = $currentGroup['name'];
                    }
                }
                if (!empty($temp)) {
                    $result['当前权限组'] = $temp;
                }
            }

            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        //$this->assignconfig("admin", ['id' => $this->auth->id]);
        $this->assign('admin', $_SESSION['think']['admin']);
        $this->assignconfig('admin', $_SESSION['think']['admin']);
    }

    /**
     * 获取教学点管理员数据
     * 直接复制 /auth/admin 的代码逻辑
     */

    private function getTeachingPointAdminData($offset, $limit, $where, $sort, $order)
    {

        $childrenGroupIds = $this->childrenGroupIds;
        $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
            ->column('id,name');
        $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
            ->field('uid,group_id')
            ->select();

        $adminGroupName = [];
        foreach ($authGroupList as $k => $v) {
            if (isset($groupName[$v['group_id']])) {
                $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
            }
        }
        $groups = $this->auth->getGroups();
        foreach ($groups as $m => $n) {
            $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        // 获取当前用户信息
        $currentUser = $this->auth->getUserInfo();

        // 构建查询条件
        $query = model("Admin")->where($where);

        // 如果不是超级管理员，需要根据学校ID和用户组层级过滤
        if (!$this->auth->isSuperAdmin()) {
            // 获取当前用户的用户组
            $currentUserGroups = $this->auth->getGroups();
            $currentGroupIds = array_column($currentUserGroups, 'id');

            // 获取当前用户组及其下级用户组
            $allowedGroupIds = [];
            foreach ($currentGroupIds as $groupId) {
                // 添加当前用户组（本级）
                $allowedGroupIds[] = $groupId;

                // 添加下级用户组
                $childGroups = Db::name('auth_group')->where('pid', $groupId)->column('id');
                $allowedGroupIds = array_merge($allowedGroupIds, $childGroups);
            }
            $allowedGroupIds = array_unique($allowedGroupIds);

            // 获取这些用户组的管理员ID
            $allowedAdminIds = Db::name('auth_group_access')
                ->where('group_id', 'in', $allowedGroupIds)
                ->column('uid');

            if (!empty($allowedAdminIds)) {
                $query = $query->where('id', 'in', $allowedAdminIds);
            }

            // 额外的学校/社区过滤
            if (!empty($currentUser['school_id'])) {
                // 学校管理员：显示同一学校的管理员（本级和下级）
                $query = $query->where('school_id', $currentUser['school_id']);
            } elseif (!empty($currentUser['community_id'])) {
                // 社区管理员：显示同一社区下所有学校的管理员（本级和下级）
                $schoolIds = Db::name('eb_school')
                    ->where('community_id', $currentUser['community_id'])
                    ->column('id');
                if (!empty($schoolIds)) {
                    $query = $query->where(function ($query) use ($currentUser, $schoolIds) {
                        $query->where('school_id', 'in', $schoolIds)
                            ->whereOr('community_id', $currentUser['community_id']);
                    });
                } else {
                    // 如果没有找到学校，只显示同一社区的管理员
                    $query = $query->where('community_id', $currentUser['community_id']);
                }
            }
        }

        // 先获取总条数
        $total = $query->count();

        // 使用原始SQL拼接方式获取数据
        $sql = "SELECT * FROM fa_admin WHERE 1=1";
        $params = [];

        // 处理where条件
        if (!empty($where)) {
            foreach ($where as $item) {
                if (is_array($item) && count($item) >= 3) {
                    list($field, $operator, $value) = $item;
                    if (in_array($field, ['username', 'nickname', 'mobile', 'email'])) {
                        $sql .= " AND {$field} {$operator} ?";
                        $params[] = $value;
                    }
                }
            }
        }

        // 如果不是超级管理员，添加权限过滤
        if (!$this->auth->isSuperAdmin()) {
            // 获取当前用户的用户组
            $currentUserGroups = $this->auth->getGroups();
            $currentGroupIds = array_column($currentUserGroups, 'id');

            // 获取当前用户组及其下级用户组
            $allowedGroupIds = [];
            foreach ($currentGroupIds as $groupId) {
                // 添加当前用户组（本级）
                $allowedGroupIds[] = $groupId;

                // 添加下级用户组
                $childGroups = Db::name('auth_group')->where('pid', $groupId)->column('id');
                $allowedGroupIds = array_merge($allowedGroupIds, $childGroups);
            }
            $allowedGroupIds = array_unique($allowedGroupIds);

            // 获取这些用户组的管理员ID
            $allowedAdminIds = Db::name('auth_group_access')
                ->where('group_id', 'in', $allowedGroupIds)
                ->column('uid');

            if (!empty($allowedAdminIds)) {
                $adminIdStr = implode(',', $allowedAdminIds);
                $sql .= " AND id IN ({$adminIdStr})";
            }

            // 额外的学校/社区过滤
            if (!empty($currentUser['school_id'])) {
                $sql .= " AND school_id = ?";
                $params[] = $currentUser['school_id'];
            } elseif (!empty($currentUser['community_id'])) {
                // 社区管理员：显示同一社区下所有学校的管理员（本级和下级）
                $schoolIds = Db::name('eb_school')
                    ->where('community_id', $currentUser['community_id'])
                    ->column('id');
                if (!empty($schoolIds)) {
                    $schoolIdStr = implode(',', $schoolIds);
                    $sql .= " AND (school_id IN ({$schoolIdStr}) OR community_id = ?)";
                    $params[] = $currentUser['community_id'];
                } else {
                    $sql .= " AND community_id = ?";
                    $params[] = $currentUser['community_id'];
                }
            }
        }

        // 排除敏感字段
        $sql = str_replace('SELECT *', 'SELECT id,username,nickname,city_id,email,mobile,avatar,loginfailure,logintime,loginip,createtime,updatetime,status,school_id,community_id', $sql);

        // 添加排序和分页
        $sql .= " ORDER BY id {$order} LIMIT {$offset}, {$limit}";

        // 执行查询
        $list = Db::query($sql, $params);
        $this->model->getLastSql();
        foreach ($list as $k => &$v) {
            $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
            $v['groups'] = implode(',', array_keys($groups));
            $v['groups_text'] = implode(',', array_values($groups));
            $list[$k]['school_id'] = model('School')->getSchool_idTextAttr($list[$k]['school_id'], $list[$k]);
            $list[$k]['community_id'] = model('Community')->getCommunity_idTextAttr($list[$k]['community_id'], $list[$k]);
        }
        unset($v);
        // 修改数据格式，使其与ajax index的返回字段一致
        $data = [];
        foreach ($list as $item) {
            $row = [
                'id' => $item['id'],
                'city_id' => model('Cityarea')->getCity_idTextAttr($item['city_id'], $item), // 城市ID
                //'city_id' => $item['city_id'], // 城市ID
                'state' => 'closed',
                'username' => $item['username'] ?: '-',
                'nickname' => $item['nickname'] ?: '-',
                'mobile' => $item['mobile'] ?: '-',
                'email' => $item['email'] ?: '-',
                'avatar' => $item['avatar'] ? cdnurl($item['avatar'], true) : letter_avatar($item['username']),
                'status' => $item['status'],
                'status_text' => $item['status'] == 'normal' ? '正常' : '禁用',
                'group_id' => 0,
                'group' => $item['groups_text'] ?: '无',
                'classes_id' => '',
                'class_name' => '-',
                'school_id' => $item['school_id'] ?? '',
                'school_name' => $item['school_id'] ?? '-',
                'ocation_id' => '',
                'ocation_name' => '-',
                'createtime' => $item['createtime'],
                'createtime_text' => date('Y-m-d H:i:s', $item['createtime']),
                'join_time' => $item['createtime'],
                'join_time_text' => $item['createtime'] ? date('Y-m-d H:i:s', $item['createtime']) : '-'
            ];
            $data[] = $row;
        }

        // 使用实际统计的总条数而不是count($list)
        $result = array("total" => $total, "rows" => $data);
        return json($result);
    }

    // 添加复制自 /auth/admin/index 的方法
    private function getAdminData($offset, $limit, $where, $sort, $order)
    {
        $query = Db::name('admin')
            ->alias('a')
            ->join('auth_group ag', 'a.group_id=ag.id', 'LEFT');

        // 处理搜索条件
        if (!empty($where)) {
            foreach ($where as $item) {
                if (is_array($item)) {
                    list($field, $operator, $value) = $item;
                    if (in_array($field, ['a.username', 'a.nickname', 'a.mobile'])) {
                        $query->where($field, $operator, $value);
                    } elseif ($field == 'ag.name') {
                        $query->where($field, $operator, $value);
                    }
                }
            }
        }

        // 获取总数
        $total = $query->count();

        // 排序和分页
        $query->field('a.id,a.username,a.nickname,a.mobile,a.email,a.avatar,a.status,a.createtime,a.jointime,ag.name as group_name')
            ->order($sort, $order)
            ->limit($offset, $limit);

        // 获取数据列表
        $list = $query->select();

        // 格式化数据
        $rows = [];
        foreach ($list as $item) {
            $row = [
                'id' => $item['id'],
                'username' => $item['username'] ?: '-',
                'nickname' => $item['nickname'] ?: '-',
                'mobile' => $item['mobile'] ?: '-',
                'email' => $item['email'] ?: '-',
                'avatar' => $item['avatar'] ? cdnurl($item['avatar'], true) : letter_avatar($item['username']),
                'status' => $item['status'],
                'status_text' => $item['status'] == 'normal' ? '正常' : '禁用',
                'group_id' => 0,
                'group' => $item['group_name'] ?: '无',
                'classes_id' => '',
                'class_name' => '-',
                'school_id' => '',
                'school_name' => '-',
                'ocation_id' => '',
                'ocation_name' => '-',
                'createtime' => $item['createtime'],
                'createtime_text' => date('Y-m-d H:i:s', $item['createtime']),
                'join_time' => $item['jointime'],
                'join_time_text' => $item['jointime'] ? date('Y-m-d H:i:s', $item['jointime']) : '-'
            ];
            $rows[] = $row;
        }

        return [
            'total' => $total,
            'rows' => $rows
        ];
    }

    /**
     * 查看学员列表
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);

        // 如果有force_html参数，强制返回HTML视图
        $forceHtml = $this->request->param('force_html');

        if ($this->request->isAjax() && !$forceHtml) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            // 添加城市和学校过滤逻辑
            $city_id = $this->request->get('cityarea_id', '');
            $school_id = $this->request->get('school_id', '');

            // 根据session中的group_id和city_id为特定用户组自动添加过滤条件
            if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                if (isset($_SESSION['think']['admin']['city_id']) && $_SESSION['think']['admin']['city_id']) {
                    $city_id = $_SESSION['think']['admin']['city_id'];
                }
            }

            $sort = ($sort == "id") ? "u.id" : $sort;
            $classes_id = $this->request->get('class_id');

            // 获取group_id参数，同时检查GET和POST请求
            $groupId = $this->request->request('group_id', '');

            // 如果没有指定groupId但有class_id，默认查询学生信息
            if (empty($groupId) && !empty($classes_id)) {
                $groupId = 1; // 默认查询学生组
            }

            if ($groupId == 4) {
                return $this->getTeachingPointAdminData($offset, $limit, $where, $sort, $order);
            } else if ($groupId == 1) {
                $query = Db::name("eb_class_student")
                    ->alias('cs')
                    ->join("fa_user u", "cs.student_id=u.id", "left")
                    ->join("fa_user_group ug", "u.group_id=ug.id", "left")
                    ->join("eb_classes c", "cs.classes_id=c.id", "left")
                    ->join("eb_school s", "c.school_id=s.id", "left")
                    ->join("fa_ocation oc", "c.ocation_id=oc.id", "left")
                    ->where($where)
                    ->group("cs.student_id")
                    ->field("cs.student_id as id,u.username,u.nickname,u.mobile,s.city_id,cs.create_time as createtime,u.email,u.avatar,cs.status,u.group_id,ug.name as group_name,c.id as classes_id,c.name as class_name,s.id as school_id,s.name as school_name,oc.id as ocation_id,oc.name as ocation_name,u.jointime as join_time");
            } else if ($groupId == 2) {
                $query = Db::name("eb_class_teacher")
                    ->alias('t')
                    ->join("fa_user u", "t.teacher_id=u.id", "left")
                    ->join("fa_user_group ug", "u.group_id=ug.id", "left")
                    ->join("eb_apply_form_item a", "a.user_id=u.id", "left")
                    ->join("eb_classes c", "a.classes_id=c.id", "left")
                    ->join("eb_school s", "c.school_id=s.id", "left")
                    ->join("fa_ocation oc", "c.ocation_id=oc.id", "left")
                    ->where($where)
                    ->group("t.teacher_id")
                    ->field("t.teacher_id as id,u.username,s.city_id,u.nickname,u.mobile,a.create_time createtime,u.email,u.avatar,t.status,u.group_id,ug.name as group_name,c.id as classes_id,c.name as class_name,s.id as school_id,s.name as school_name,oc.id as ocation_id,oc.name as ocation_name,u.jointime as join_time");
            } else if ($groupId == 3) {
                $query = Db::name("eb_class_manager")
                    ->alias('cm')
                    ->join("fa_user u", "cm.manager_id=u.id", "left")
                    ->join("fa_user_group ug", "u.group_id=ug.id", "left")
                    ->join("eb_apply_form_item a", "a.user_id=u.id", "left")
                    ->join("eb_classes c", "a.classes_id=c.id", "left")
                    ->join("eb_school s", "c.school_id=s.id", "left")
                    ->join("fa_ocation oc", "c.ocation_id=oc.id", "left")
                    ->where($where)
                    ->group("cm.manager_id")
                    ->field("cm.manager_id as id,u.username,s.city_id,u.nickname,u.mobile,a.create_time createtime,u.email,u.avatar,cm.status,u.group_id,ug.name as group_name,c.id as classes_id,c.name as class_name,s.id as school_id,s.name as school_name,oc.id as ocation_id,oc.name as ocation_name,u.jointime as join_time");
            }else {
                $query = Db::name("eb_class_student")
                    ->alias('cs')
                    ->join("fa_user u", "cs.student_id=u.id", "left")
                    ->join("fa_user_group ug", "u.group_id=ug.id", "left")
                    ->join("eb_classes c", "cs.classes_id=c.id", "left")
                    ->join("eb_school s", "c.school_id=s.id", "left")
                    ->join("fa_ocation oc", "c.ocation_id=oc.id", "left")
                    ->where($where)
                    ->group("cs.student_id")
                    ->field("cs.student_id as id,u.username,u.nickname,u.mobile,s.city_id,cs.create_time as createtime,u.email,u.avatar,cs.status,u.group_id,ug.name as group_name,c.id as classes_id,c.name as class_name,s.id as school_id,s.name as school_name,oc.id as ocation_id,oc.name as ocation_name,u.jointime as join_time");


            }
            // 添加城市过滤条件
            if ($city_id) {
                $query->where('s.city_id', $city_id);
            }

            // 添加学校过滤条件
            if ($school_id) {
                $query->where('s.id', $school_id);
            }

            // 如果group_id参数存在且不为0，则添加筛选条件
            if ($groupId !== '' && $groupId != 0) {
                $query->where('u.group_id', $groupId);
            }

            // 如果有特定的班级ID，添加过滤条件
            if (!empty($classes_id)) {
                $query->where('c.id', $classes_id);
            }

            $list = $query->limit($offset, $limit)->select();


            //    Db::name("user")->getlastsql()
            // 修改总数查询逻辑
            $totalQuery = Db::name("eb_class_student")
                ->alias('cs')
                ->join("fa_user u", "cs.student_id=u.id", "left")
                ->join("eb_classes c", "cs.classes_id=c.id", "left")
                ->where($where)
                ->group("cs.student_id");

            // 如果group_id参数存在且不为0，则添加筛选条件
            if ($groupId !== '' && $groupId != 0) {
                $totalQuery->where('u.group_id', $groupId);
            }

            // 如果有特定的班级ID，添加过滤条件
            if (!empty($classes_id)) {
                $totalQuery->where('c.id', $classes_id);
            }

            $total = $totalQuery->count();

            // 处理数据 
            $rows = [];
            foreach ($list as $key => $item) {
                if (!$item['id']) continue;
                // 使用用户ID和班级ID组合作为唯一标识
                $row = [
                    'id' => $item['id'],  // 组合用户ID和班级ID确保唯一性
                    'city_id' => model('Cityarea')->getCity_idTextAttr($item['city_id'], $item),
                    'username' => $item['username'],
                    'nickname' => $item['nickname'] ?: '-',
                    'mobile' => $item['mobile'] ?: '-',
                    'email' => $item['email'] ?: '-',
                    'avatar' => $item['avatar'] ? cdnurl($item['avatar'], true) : letter_avatar($item['nickname']),
                    'status' => $item['status'],
                    'status_text' => $item['status'] == 'normal' || $item['status'] == 1 ? '审核通过' : ($item['status'] == '-1' ? '审核不通过' : '未处理'),
                    'group_id' => $item['group_id'],
                    // 修复：确保group字段是字符串而不是对象，避免前端JS错误
                    'group' => $item['group_name'] ?: '未知',
                    'classes_id' => $item['classes_id'],
                    'class_name' => $item['class_name'],
                    'school_id' => model('School')->getSchool_idTextAttr($item['school_id'], $item),
                    'city_id' => model('Cityarea')->getCity_idTextAttr($item['city_id'], $item),
                    //$list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id'],$list[$i]);
                    //$list[$i]['school_id']=model('School')->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
                    'school_name' => $item['school_name'] ?: '-',
                    'ocation_id' => $item['ocation_id'],
                    'ocation_name' => $item['ocation_name'],
                    //'createtime' => $item['createtime'],
                    //'createtime_text' => date('Y-m-d H:i:s', $item['createtime']),
                    //'logintime' => $item['logintime'],
                    //'logintime_text' => $item['logintime'] ? date('Y-m-d H:i:s', $item['logintime']) : '从未登录',
                    'join_time' => $item['join_time'],
                    'join_time_text' => date('Y-m-d H:i:s', $item['join_time'])
                ];
                $rows[] = $row;
            }

            $result = ['total' => $total, 'rows' => $rows];

            return json($result);
        }

        // 获取用户组列表
        $groupList = Db::name('fa_user_group')->where('status', 1)->field('id,name')->select();
        $this->view->assign('groupList', $groupList);
        $this->view->assign('groupId', $this->request->param('group_id', ''));
        // 修复JavaScript错误：确保groupId是字符串类型
        $this->assignconfig('groupId', (string)$this->request->param('group_id', ''));
        return $this->view->fetch();
    }

    /**
     * 添加学员
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            $params = $this->preExcludeFields($params);

            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $params[$this->dataLimitField] = $this->auth->id;
            }

            // 从session中自动获取city_id和school_id并插入
            if (isset($_SESSION['think']['admin']['city_id']) && $_SESSION['think']['admin']['city_id']) {
                $params['city_id'] = $_SESSION['think']['admin']['city_id'];
            }
            if (isset($_SESSION['think']['admin']['school_id']) && $_SESSION['think']['admin']['school_id']) {
                $params['school_id'] = $_SESSION['think']['admin']['school_id'];
            }

            $result = false;
            Db::startTrans();
            try {
                // 插入用户数据
                $params['salt'] = \fast\Random::alnum();
                $params['password'] = \addons\loginbg\controller\Index::getEncryptPassword($params['password'], $params['salt']);
                $params['avatar'] = '';
                $params['createtime'] = time();
                $params['updatetime'] = time();

                $result = Db::name("user")->insertGetId($params);
                Db::commit();
            } catch (\think\exception\PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }

        return $this->view->fetch();
    }

    /**
     * 编辑学员
     */
    public function edit($ids = null)
    {
        $row = Db::name("user")->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            $params = $this->preExcludeFields($params);

            // 在当前记录的city_id或school_id为空时，从session中获取并插入
            if (empty($row['city_id']) && isset($_SESSION['think']['admin']['city_id']) && $_SESSION['think']['admin']['city_id']) {
                $params['city_id'] = $_SESSION['think']['admin']['city_id'];
            }
            if (empty($row['school_id']) && isset($_SESSION['think']['admin']['school_id']) && $_SESSION['think']['admin']['school_id']) {
                $params['school_id'] = $_SESSION['think']['admin']['school_id'];
            }

            if (isset($params['password']) && !empty($params['password'])) {
                $params['salt'] = \fast\Random::alnum();
                $params['password'] = \addons\loginbg\controller\Index::getEncryptPassword($params['password'], $params['salt']);
            } else {
                unset($params['password']);
            }

            // 处理时间字段，确保格式正确
            $timeFields = ['jointime', 'createtime', 'updatetime', 'logintime'];
            foreach ($timeFields as $field) {
                if (isset($params[$field])) {
                    if (is_string($params[$field]) && !empty($params[$field])) {
                        // 如果是字符串格式的日期，转换为时间戳
                        $timestamp = strtotime($params[$field]);
                        if ($timestamp !== false&&$timestamp > 0) {
                            $params[$field] = $timestamp;
                        } else {
                            // 如果转换失败，移除该字段
                            unset($params[$field]);
                        }
                    } elseif (empty($params[$field]) && $field === 'jointime') {
                        // 如果 jointime 为空，设置为当前时间戳
                        $params[$field] = time();
                    } elseif (empty($params[$field])) {
                        // 其他时间字段为空时，移除该字段
                        unset($params[$field]);
                    }
                }
            }

            // 移除不应该被更新的字段
            $excludeFields = ['id', 'createtime']; // createtime 通常不应该被更新
            foreach ($excludeFields as $field) {
                if (isset($params[$field])) {
                    unset($params[$field]);
                }
            }

            $result = false;
            Db::startTrans();
            try {
                $params['updatetime'] = time();

                // 调试信息：记录要更新的参数
                \think\Log::info('Studentmanager edit params: ' . json_encode($params));

                $result = Db::name("user")->where('id', $ids)->update($params);
                Db::commit();
            } catch (\think\exception\PDOException $e) {
                Db::rollback();
                \think\Log::error('Studentmanager edit PDO error: ' . $e->getMessage());
                $this->error('数据更新失败：' . $e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                \think\Log::error('Studentmanager edit error: ' . $e->getMessage());
                $this->error('更新失败：' . $e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除学员
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }

        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $count = Db::name("user")->where('id', 'in', $ids)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 获取管理员可管理的教学点ID列表
     */
    private function getManageableOcationIds()
    {
        $admin = $this->auth->getUserInfo();
        if (!$admin) {
            return [];
        }

        $ocationIds = [];

        // 学校管理员：管理该学校下的所有教学点
        if (!empty($admin['school_id'])) {
            $schoolOcations = Db::name('ocation')
                ->where('rel_type', 1)
                ->where('rel_id', $admin['school_id'])
                ->where('status', 1)
                ->column('id');
            $ocationIds = array_merge($ocationIds, $schoolOcations);
        }

        // 社区管理员：管理该社区下所有学校的教学点
        if ($_SESSION['think']['admin']['group_id'] == 8) {
            // 获取社区下的所有学校
            $schoolIds = Db::name('eb_school_community')
                ->where('community_id', $admin['community_id'])
                ->column('id');

            if (!empty($schoolIds)) {
                $communityOcations = Db::name('ocation')
                    ->where('rel_type', 1)
                    ->where('rel_id', 'in', $schoolIds)
                    ->where('status', 1)
                    ->column('id');
                $ocationIds = array_merge($ocationIds, $communityOcations);
            }

            // 同时也包括直接属于社区的教学点
            $directCommunityOcations = Db::name('ocation')
                ->where('rel_type', 2)
                ->where('rel_id', $admin['community_id'])
                ->where('status', 1)
                ->column('id');
            $ocationIds = array_merge($ocationIds, $directCommunityOcations);
        }

        // 递归获取所有子教学点
        $allOcationIds = $this->getAllChildOcationIds($ocationIds);

        return array_unique($allOcationIds);
    }

    /**
     * 递归获取所有子教学点ID
     * @param array $parentIds 父级ID数组
     * @param array $processedIds 已处理的ID数组，用于防止循环引用
     * @return array 所有子教学点ID数组
     */
    private function getAllChildOcationIds($parentIds, &$processedIds = [])
    {
        if (empty($parentIds)) {
            return [];
        }

        // 过滤掉已经处理过的ID，避免循环引用
        $parentIds = array_diff($parentIds, $processedIds);
        if (empty($parentIds)) {
            return [];
        }

        // 将当前处理的ID添加到已处理列表
        $processedIds = array_merge($processedIds, $parentIds);
        $allIds = $parentIds;

        // 查找子教学点
        $childIds = Db::name('ocation')
            ->where('pid', 'in', $parentIds)
            ->where('status', 1)
            ->column('id');

        if (!empty($childIds)) {
            // 递归获取子级ID，并传入已处理的ID列表
            $childIds = array_diff($childIds, $processedIds);
            if (!empty($childIds)) {
                $allIds = array_merge($allIds, $this->getAllChildOcationIds($childIds, $processedIds));
            }
        }

        return array_unique($allIds);
    }



    /**
     * 查看学员详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        // 检查权限
        $ocationIds = $this->getManageableOcationIds();
        if (empty($ocationIds)) {
            $this->error('无权限查看该学员信息');
        }

        // 检查该用户是否在管辖范围内
        $userInRange = Db::name('eb_apply_form_item')
            ->alias('a')
            ->join('eb_classes c', 'c.id = a.classes_id')
            ->where('a.user_id', $ids)
            ->where('c.ocation_id', 'in', $ocationIds)
            ->where('a.status', 1)
            ->find();

        if (!$userInRange) {
            $this->error('无权限查看该学员信息');
        }

        // 获取用户参与的班级列表
        $classes = Db::name('eb_apply_form_item')
            ->alias('a')
            ->join('eb_classes c', 'c.id = a.classes_id')
            ->join('fa_ocation o', 'o.id = c.ocation_id')
            ->where('a.user_id', $ids)
            ->where('c.ocation_id', 'in', $ocationIds)
            ->where('a.status', 1)
            ->field('c.id,c.name as class_name,o.name as ocation_name,a.createtime as join_time')
            ->select();

        foreach ($classes as &$class) {
            $class['join_time_text'] = date('Y-m-d H:i:s', $class['join_time']);
        }

        // 获取用户组信息
        $group = Db::name('user_group')->where('id', $row['group_id'])->find();
        $row['group_name'] = $group ? $group['name'] : '未知';

        $row['avatar'] = $row['avatar'] ? cdnurl($row['avatar'], true) : letter_avatar($row['nickname']);
        $row['createtime_text'] = date('Y-m-d H:i:s', $row['createtime']);
        $row['logintime_text'] = $row['logintime'] ? date('Y-m-d H:i:s', $row['logintime']) : '从未登录';
        $row['classes'] = $classes;

        unset($row['password'], $row['salt']);

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 更新学员状态
     */
    public function changeStatus()
    {
        $ids = $this->request->post('ids');
        $status = $this->request->post('status');
        $group_id = $this->request->post('group_id');

        if (empty($ids) || !isset($status)) {
            $this->error('参数不完整');
        }

        // 验证状态值是否合法
        if (!in_array($status, ['0', 'normal', '-1'])) {
            $this->error('状态参数错误');
        }

        $idsArray = explode(',', $ids);
        $result = false; // 初始化$result变量

        // 批量更新状态
        if ($group_id == 1) {
            $status = ($status == "normal" || $status == "1") ? "1" : $status;
            $result = Db::name('eb_class_student')
                ->where('id', 'in', $idsArray)
                ->update([
                    'status' => $status,
                    'update_time' => date("Y-m-d H:i:s", time()),
                ]);
        } else if ($group_id == 2) {
            $status = ($status == "normal" || $status == "1") ? "1" : $status;
            $result = Db::name('eb_class_teacher')
                ->where('teacher_id', 'in', $idsArray)
                ->update([
                    'status' => $status,
                    'audit_time' => date("Y-m-d H:i:s", time()),
                ]);
        } else if ($group_id == 3) {
            $status = ($status == "normal" || $status == "1") ? "1" : $status;
            $result = Db::name('eb_class_manager')
                ->where('manager_id', 'in', $idsArray)
                ->update([
                    'status' => $status,
                    'audit_time' => date("Y-m-d H:i:s", time()),
                ]);
        } else {
            $this->error('无效的用户组ID');
        }

        if ($result) {
            $this->success('状态更新成功');
        } else {
            $this->error('状态更新失败');
        }
    }

    /**
     * 获取统计信息
     */
    public function statistics()
    {
        // 获取可管理的教学点ID
        $ocationIds = $this->getManageableOcationIds();
        if (empty($ocationIds)) {
            return json(['code' => 0, 'msg' => '暂无数据', 'data' => []]);
        }

        // 查询在管辖教学点有活动的用户
        $userIds = Db::name('eb_apply_form_item')
            ->alias('a')
            ->join('eb_classes c', 'c.id = a.classes_id')
            ->where('c.ocation_id', 'in', $ocationIds)
            ->where('a.status', 1)
            ->column('a.user_id');

        if (empty($userIds)) {
            return json(['code' => 0, 'msg' => '暂无数据', 'data' => []]);
        }

        $userIds = array_unique($userIds);

        // 总学员数
        $totalStudents = count($userIds);

        // 按状态统计
        $statusStats = Db::name('user')
            ->where('id', 'in', $userIds)
            ->field('status, count(*) as count')
            ->group('status')
            ->select();

        // 按用户组统计
        $groupStats = Db::name('user')
            ->alias('u')
            ->join('fa_user_group g', 'u.group_id = g.id', 'LEFT')
            ->where('u.id', 'in', $userIds)
            ->field('u.group_id, g.name as group_name, count(*) as count')
            ->group('u.group_id')
            ->select();

        // 今日新增学员
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayNew = Db::name('user')
            ->where('id', 'in', $userIds)
            ->where('createtime', '>=', $todayStart)
            ->count();

        // 本月新增学员
        $monthStart = strtotime(date('Y-m-01 00:00:00'));
        $monthNew = Db::name('user')
            ->where('id', 'in', $userIds)
            ->where('createtime', '>=', $monthStart)
            ->count();

        return json([
            'code' => 1,
            'msg' => '获取成功',
            'data' => [
                'total_students' => $totalStudents,
                'today_new' => $todayNew,
                'month_new' => $monthNew,
                'status_stats' => $statusStats,
                'group_stats' => $groupStats
            ]
        ]);
    }

    /**
     * 导出学员数据
     */
    public function export()
    {
        // 添加调试日志
        \think\Log::info('Export method called');
        \think\Log::info('Request params: ' . json_encode($this->request->param()));
        
        $groupId = $this->request->get('group_id', '');
        $keyword = $this->request->get('keyword', '');

        // 简化导出逻辑，先测试基本功能
        try {
            // 直接从用户表导出数据，不依赖教学点权限
            $where = [];
            if (!empty($keyword)) {
                $where[] = ['username|nickname|mobile', 'like', '%' . $keyword . '%'];
            }
            if (!empty($groupId)) {
                $where[] = ['group_id', '=', $groupId];
            }

            // 查询用户列表
            $list = Db::name('user')
                ->where($where)
                ->field('id,username,nickname,mobile,email,group_id,status,createtime,logintime')
                ->order('id desc')
                ->limit(1000) // 限制导出数量
                ->select();

            \think\Log::info('Found ' . count($list) . ' users to export');

            if (empty($list)) {
                $this->error('没有找到符合条件的数据');
            }

            // 处理导出数据
            $exportData = [];
            foreach ($list as $item) {
                $exportData[] = [
                    'ID' => $item['id'],
                    '用户名' => $item['username'],
                    '昵称' => $item['nickname'] ?: '-',
                    '手机号' => $item['mobile'] ?: '-',
                    '邮箱' => $item['email'] ?: '-',
                    '用户组ID' => $item['group_id'],
                    '状态' => $item['status'] == 'normal' ? '正常' : '其他',
                    '注册时间' => date('Y-m-d H:i:s', $item['createtime']),
                    '最后登录' => $item['logintime'] ? date('Y-m-d H:i:s', $item['logintime']) : '从未登录'
                ];
            }

            // 导出CSV
            $filename = '学员数据_' . date('YmdHis') . '.csv';
            $this->exportCsv($filename, array_keys($exportData[0]), $exportData);
            
        } catch (\Exception $e) {
            \think\Log::error('Export error: ' . $e->getMessage());
            $this->error('导出失败：' . $e->getMessage());
        }


    }

    /**
     * 测试导出功能
     */
    public function testExport()
    {
        // 简单的测试数据
        $testData = [
            ['ID', '用户名', '昵称', '手机号'],
            ['1', 'test1', '测试用户1', '13800138001'],
            ['2', 'test2', '测试用户2', '13800138002'],
        ];
        
        $filename = '测试导出_' . date('YmdHis') . '.csv';
        
        set_time_limit(0);
        ini_set('memory_limit', '1024M');

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $fp = fopen('php://output', 'w');
        // 添加BOM头，解决中文乱码
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
        
        // 写入数据
        foreach ($testData as $row) {
            fputcsv($fp, $row);
        }
        fclose($fp);
        exit;
    }

    /**
     * 导出CSV文件
     */
    protected function exportCsv($filename, $header, $data)
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $fp = fopen('php://output', 'w');
        // 添加BOM头，解决中文乱码
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
        // 写入表头
        fputcsv($fp, $header);
        // 写入数据
        foreach ($data as $row) {
            fputcsv($fp, $row);
        }
        fclose($fp);
        exit;
    }
}
